<mat-drawer-container class="flex-1 w-full" [hasBackdrop]="false" [autosize]="true">
    <mat-drawer #drawer opened mode="side" ngmResizer [resizerWidth]="230">
        <div class="h-full flex flex-col justify-start items-stretch">
            <mat-toolbar class="pac-sub-toolbar flex justify-between items-center gap-2" displayDensity="compact">
                <button mat-icon-button displayDensity="compact" (click)="drawer.toggle()">
                    <mat-icon fontSet="material-icons-round">segment</mat-icon>
                </button>

                <span>{{ 'PAC.MODEL.QUERY.TableSchema' | translate: {Default: "Table Schema"} }}</span>

                <span class="flex flex-1"></span>

                <button mat-icon-button color="warn" displayDensity="cosy" class="pac-cdk-drop__recycle-bin"
                    cdkDropList
                    [cdkDropListEnterPredicate]="entityDeletePredicate"
                    (cdkDropListDropped)="deleteEntity($event)"
                >
                    <mat-icon color="warn" fontSet="material-icons-round">delete</mat-icon>
                </button>
            </mat-toolbar>

            <div id="pac-model__query-entities" class="pac-model-query__schema pac-cdk-drop__list flex-1 flex flex-col overflow-auto"
                cdkDropList
                [cdkDropListEnterPredicate]="editorDropPredicate"
                (cdkDropListDropped)="dropEntity($event)"
            >
              @for (entity of entities(); track entity) {
                <ngm-entity-schema
                    [dataSettings]="{dataSource: dataSourceName, entitySet: entity}"
                    [capacities]="[
                        EntityCapacity.Dimension,
                        EntityCapacity.Measure,
                        EntityCapacity.Parameter
                    ]"
                />
              }
            </div>
        </div>

        <div ngmResizerBar resizerBarPosition="right"
            cdkDrag
            cdkDragLockAxis="x"
        ></div>
    </mat-drawer>

    <mat-drawer-content>
        <ngm-splitter class="ngm-layout-container-secondary flex-1 w-full h-full" [type]="1">
            <ngm-splitter-pane size='50%' class="flex flex-col justify-end items-stretch z-[101]">
                <mat-toolbar class="pac-sub-toolbar pac-toolbar__editor flex justify-start items-center gap-2"
                    displayDensity="compact">
                    <button *ngIf="!drawer.opened" mat-icon-button displayDensity="compact" (click)="drawer.toggle()">
                        <mat-icon fontSet="material-icons-round">segment</mat-icon>
                    </button>

                    <button mat-flat-button color="primary" displayDensity="compact" [disabled]="!statement"
                        matTooltip=" {{ 'PAC.KEY_WORDS.ShortcutKey' | translate: {Default: 'Shortcut Key'} }}: F8"
                        (click)="run()">
                        <mat-icon fontSet="material-icons-round">arrow_right</mat-icon>

                        <span *ngIf="textSelection?.text">
                            {{ 'PAC.MENU.RUN_BY_SELECTION' | translate: {Default: "Run By Selection"} }}
                        </span>
                        <span *ngIf="!textSelection?.text">
                            {{ 'PAC.MENU.RUN' | translate: {Default: "Run"} }}
                        </span>

                    </button>

                    <!-- <button mat-button color="primary" displayDensity="compact" [disabled]="!statement">
                        <mat-icon fontSet="material-icons-round">agriculture</mat-icon>
                        校验</button> -->
                    <button mat-button color="primary" displayDensity="compact"
                        [disabled]="!dirty||!statement"
                        (click)="save()">
                        <mat-icon fontSet="material-icons-round">new_label</mat-icon>
                        {{ 'PAC.KEY_WORDS.SAVE' | translate: {Default: 'Save'} }}
                    </button>
                    
                    <ng-container *ngIf="isWasm()">
                        <button mat-button color="primary" displayDensity="compact"
                            [disabled]="!statement || dbInitialization === selectedStatement"
                            (click)="saveAsDBScript()"
                        >
                            <mat-icon fontSet="material-icons-outlined" >save_as</mat-icon>
                            {{ 'PAC.MODEL.QUERY.SaveAsDBInit' | translate: {Default: "Save as DB Init Script"} }}
                        </button>
                    </ng-container>
        
                    <!-- <button *ngIf="useSaveAsSQL$ | async" mat-button color="primary" displayDensity="compact"
                        [disabled]="!statement"
                        (click)="saveAsModel()">
                        <mat-icon fontSet="material-icons-outlined" >database</mat-icon>
                        {{ 'PAC.MODEL.QUERY.SaveAsModel' | translate: {Default: "Save As Model"} }}
                    </button> -->

                    <span class="flex-1 flex"></span>

                    <button mat-icon-button displayDensity="compact" 
                        (click)="triggerUndo()">
                        <mat-icon fontSet="material-icons-round">undo</mat-icon>
                    </button>
                    <button mat-icon-button displayDensity="compact" 
                        (click)="triggerRedo()">
                        <mat-icon fontSet="material-icons-round">redo</mat-icon>
                    </button>
                    <button mat-icon-button displayDensity="compact" matTooltip="🔍{{ 'PAC.KEY_WORDS.Search' | translate: {Default: 'Search'} }}"
                        (click)="triggerFind()">
                        <mat-icon fontSet="material-icons-round">search</mat-icon>
                    </button>
                    <button mat-icon-button displayDensity="compact" matTooltip="⛔{{ 'PAC.KEY_WORDS.Clear' | translate: {Default: 'Clear'} }}"
                        (click)="triggerClear()">
                        <mat-icon fontSet="material-icons-round">playlist_remove</mat-icon>
                    </button>

                    @if (isMDX()) {
                        <button mat-icon-button displayDensity="compact" matTooltip="📦{{ 'PAC.KEY_WORDS.Compact' | translate: {Default: 'Compact'} }}"
                            (click)="triggerCompress()">
                            <mat-icon fontSet="material-icons-outlined">folder_zip</mat-icon>
                        </button>
                    }

                    <button mat-icon-button displayDensity="compact" matTooltip="💡{{ 'PAC.KEY_WORDS.Format' | translate: {Default: 'Format'} }}"
                        (click)="triggerFormat()">
                        <mat-icon fontSet="material-icons-round">format_indent_increase</mat-icon>
                    </button>
                </mat-toolbar>

                @if (isMDX()) {
                    <ngm-mdx-editor #editor class="pac-cdk-drop__list pac-cdk-drop__area flex-1 w-full h-full"
                        [theme]="themeName()"
                        [entityType]="entityType()"
                        [(ngModel)]="statement"
                        (selectionChange)="onSelectionChange($event)"
                        (keyDown)="onEditorKeyDown($event)"

                        cdkDropList
                        [cdkDropListEnterPredicate]="editorDropPredicate"
                        (cdkDropListDropped)="drop($event)"
                        />
                } @else {
                    <ngm-sql-editor #editor class="pac-cdk-drop__list pac-cdk-drop__area flex-1 w-full h-full"
                        [theme]="themeName()"
                        [entitySets]="tables$ | async"
                        [(ngModel)]="statement"
                        [disabled]="answering()"
                        (selectionChange)="onSelectionChange($event)"
                        (keyDown)="onEditorKeyDown($event)"
        
                        cdkDropList
                        [cdkDropListEnterPredicate]="editorDropPredicate"
                        (cdkDropListDropped)="drop($event)"
                    />
                }
            </ngm-splitter-pane>
            <ngm-splitter-pane class="relative flex flex-col justify-start items-stretch">
                <mat-toolbar class="pac-nav-toolbar" displayDensity="compact">
                    <button mat-icon-button displayDensity="compact" class="pac-nav-tab__close" [matMenuTriggerFor]="menu">
                        <mat-icon>more_vert</mat-icon>
                    </button>

                    <nav mat-tab-nav-bar id="pac-model__query-results" color="accent" mat-stretch-tabs="false" mat-align-tabs="start" class="flex-1"
                        [tabPanel]="tabPanel"
                        cdkDropList
                        [cdkDropListData]="results"
                    >
                        <span mat-tab-link (click)="activeResult = result"
                            [active]="activeResult === result"
                            *ngFor="let result of results; index as i"
                            cdkDrag
                            [cdkDragData]="result"
                            >

                            <span class="pac-nav-tab__label"
                                matTooltipClass="pac-model-query__statement-tip"
                            >
                                {{ 'PAC.MENU.RESULTS' | translate: {Default: "Results"} }}
                            </span>
        
                            <button mat-icon-button displayDensity="compact" class="pac-nav-tab__close" ngmAppearance="danger"
                                (click)="deleteResult(i);$event.stopPropagation();">
                                <mat-icon>cancel</mat-icon>
                            </button>
                        </span>
                    </nav>
                </mat-toolbar>
                <div *ngIf="loading$ | async" class="absolute top-0 left-0 w-full h-full flex flex-col justify-center items-center z-[101] bg-gray-500/10 backdrop-blur-lg">
                    <div class="emoji-loader" style="position: relative; height: 80px;"></div>
                    <button mat-stroked-button (click)="cancelQuery()">
                        {{ 'PAC.KEY_WORDS.Cancel' | translate: {Default: 'Cancel'} }}
                    </button>
                </div>
    
                <mat-progress-bar *ngIf="loading$ | async" mode="query" class="pac-model-query__progress-bar z-[102]"></mat-progress-bar>

                <mat-tab-nav-panel #tabPanel class="pac-cdk-drop__list pac-cdk-drop__area flex flex-col overflow-hidden"
                    cdkDropList
                    [cdkDropListEnterPredicate]="editorDropPredicate"
                    (cdkDropListDropped)="dropTable($event)">
                  @if (activeResult) {
                    <div class="pac-model-ql-lab__stats">
                        <button mat-icon-button displayDensity="compact"
                            [matTooltip]="'PAC.KEY_WORDS.EXPORT' | translate: {Default: 'Export'}"
                            matTooltipPosition="above"
                            (click)="export()">
                            <mat-icon>file_download</mat-icon>
                        </button>

                        <mat-icon fontSet="material-icons-outlined" displayDensity="compact"
                            [matTooltip]="activeResult.statement">info</mat-icon>
                        <span>
                        {{ 'PAC.MODEL.QUERY.TotalRecords' | translate: {Default: "Total Records"} }}
                        : {{activeResult.stats?.numberOfEntries}}</span>
                        <span *ngIf="activeResult.stats?.numberOfEntries > 1000">
                        , {{ 'PAC.MODEL.QUERY.PreviewTop1000' | translate: {Default: "Preview Top 1000"} }}.
                        </span>

                    </div>
                  }

                    <div *ngIf="activeResult?.error" class="pac-result flex-1">
                        <div class="bug font-notoColorEmoji" >🐞</div>
                        <div class="description">
                            {{activeResult.error}}
                        </div>
                    </div>

                    <ng-container *ngIf="!activeResult?.error">
                        <div *ngIf="activeResult && !activeResult?.data" class="pac-result flex-1">
                            <div class="bug font-notoColorEmoji">✔️</div>
                            <div class="description">
                            </div>
                        </div>

                        <ngm-table *ngIf="activeResult?.preview" class="pac-model-ql-lab__result ngm-data-preview striped"
                            [columns]="activeResult?.columns"
                            [data]="activeResult?.preview"
                            [paging]="true"
                        ></ngm-table>
                    </ng-container>
                </mat-tab-nav-panel>
        
                <ng-template #errorResult>
                    <div class="pac-result w-full h-full absolute top-0 left-0">
                        <div class="bug font-notoColorEmoji">🐞</div>
                        <div class="description">
                            {{_error()}}
                        </div>
                    </div>
                </ng-template>
                
            </ngm-splitter-pane>
        </ngm-splitter>
        
    </mat-drawer-content>
</mat-drawer-container>

<mat-menu #menu="matMenu" class="ngm-density__compact ngm-density__compact">
    <button mat-menu-item (click)="export()">
        <mat-icon>file_download</mat-icon>
        <span>{{ 'PAC.KEY_WORDS.EXPORT' | translate: {Default: 'Export'} }}</span>
    </button>

    <mat-divider></mat-divider>

    <button mat-menu-item ngmAppearance="danger" (click)="closeAllResults()">
        <mat-icon>close</mat-icon>
        <span>{{ 'PAC.KEY_WORDS.CLOSE_ALL' | translate: {Default: "Close All"} }}</span>
    </button>
</mat-menu>


<ng-template #tableTemplate let-message="message">
  @if (message.data['header']) {
    <div >{{message.data['header']}}</div>
  }
    <ngm-table class="max-w-full rounded-lg border overflow-hidden"
        [columns]="message.data['columns']"
        [data]="message.data['content']"
        paging
        [pageSizeOptions]="[10, 20, 50, 100]"
    ></ngm-table>
</ng-template>